package com.googlecode.stemwijzer.client.rest;

import java.util.Map;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * The Class AbstractRestService.
 * 
 * @author jeroen.brosens
 */
public abstract class AbstractRestService {

	private static final int JSONP_REQUEST_TIMEOUT = 3000;

	/**
	 * jsonpRequest.
	 * 
	 * @param resourceUrl
	 *            the resource url
	 * @param queryParams
	 *            the query params
	 * @param callback
	 *            the callback
	 */
	public void jsonpRequest(final String resourceUrl, final Map<String, String> queryParams,
			final AsyncCallback<String> callback) {

		JsonpRequestBuilder builder = new JsonpRequestBuilder();
		builder.setTimeout(JSONP_REQUEST_TIMEOUT);

		// Build request URI
		String requestUri = resourceUrl;

		if (queryParams != null) {
			requestUri += "?";
			int i = 0;

			for (String queryParam : queryParams.keySet()) {
				requestUri += queryParam + "=" + queryParams.get(queryParam);

				if (++i < queryParams.size()) {
					requestUri += "&";
				}
			}
		}

		builder.requestObject(URL.encode(requestUri), new AsyncCallback<JavaScriptObject>() {

			@Override
			public void onSuccess(final JavaScriptObject jso) {
				// convert JavaScript object to JSON string
				final String json = new JSONObject(jso).toString();

				Log.debug("JSONP request succeeded on resource [" + resourceUrl + "], response: [" + json + "]");

				callback.onSuccess(json);
			}

			@Override
			public void onFailure(final Throwable t) {
				Log.error("JSONP request failed on resource [" + resourceUrl + "], see subsequent error messages");
				callback.onFailure(t);
			}
		});
	}
}
